package com.example.security.config;

import com.example.security.authentication.SmsAuthenticationFilter;
import com.example.security.authentication.dao.SmsAuthenticationProvider;
import com.example.security.provisioning.CustomUserDetailsManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.*;

/**
 * @className: SecurityConfig
 * @author: YTF
 * @date: 2025/4/30 21:15
 * @description: 安全过滤器
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, SmsAuthenticationFilter smsAuthenticationFilter
    ) throws Exception {

        http
//                .csrf(Customizer.withDefaults()) // 默认开启
                .csrf(AbstractHttpConfigurer::disable)  // 关闭 CSRF
                .httpBasic(Customizer.withDefaults())
                .formLogin(form -> form
                        .loginPage("/login")
                        .defaultSuccessUrl("/")
                        .failureUrl("/login?error")
                )
//                .logout(logout -> logout
//                        .logoutUrl("/logout")  // 指定登出端点
//                        .logoutSuccessUrl("/login?logout")
//                        .invalidateHttpSession(true)
//                        .deleteCookies("JSESSIONID")
//                )
//                .formLogin(Customizer.withDefaults())
                .logout(Customizer.withDefaults())
                .authorizeHttpRequests(
                        authorize -> authorize
//                                .requestMatchers("/login", "/login/sms", "/error", "/open/**", "/css/**", "/js/**").anonymous()
                                .requestMatchers("/admin/**").hasRole("ADMIN")
                                .requestMatchers("/user/**").hasRole("USER")
                                .requestMatchers("/login", "/login/sms", "/error", "/open/**", "/css/**", "/js/**").permitAll()
                                .anyRequest().authenticated()
                )
//                .authenticationProvider(new SmsAuthenticationProvider())
//                .addFilterAfter(new TenantFilter(), AnonymousAuthenticationFilter.class)
                // 添加手机验证码过滤器
                .addFilterBefore(smsAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)

        ;

        return http.build();
    }

    // 手机认证过滤器
    @Bean
    public SmsAuthenticationFilter phoneAuthenticationFilter(
            AuthenticationManager authenticationManager,
            AuthenticationSuccessHandler successHandler,
            AuthenticationFailureHandler failureHandler
    ) {
        SmsAuthenticationFilter filter = new SmsAuthenticationFilter();
        filter.setAuthenticationManager(authenticationManager);
        filter.setAuthenticationSuccessHandler(successHandler);
        filter.setAuthenticationFailureHandler(failureHandler);
        return filter;
    }

    // 密码编码器必须显式定义
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    @ConditionalOnMissingBean(UserDetailsService.class)
    CustomUserDetailsManager userDetailsService() {
        return new CustomUserDetailsManager();
    }

    // 显式注册 DaoAuthenticationProvider
    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider(
            PasswordEncoder passwordEncoder,
            UserDetailsService userDetailsService
    ) {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder);
        return provider;
    }

    // 认证管理器配置
    @Bean
    public AuthenticationManager authenticationManager(
            HttpSecurity http,
            DaoAuthenticationProvider daoProvider, // 注入 DaoProvider
            SmsAuthenticationProvider smsProvider
    ) throws Exception {
        AuthenticationManagerBuilder builder =
                http.getSharedObject(AuthenticationManagerBuilder.class);

        builder.authenticationProvider(daoProvider) // 显式添加 DaoProvider
                .authenticationProvider(smsProvider);

        return builder.build();
    }

    // 公共处理器配置（成功/失败跳转）
    @Bean
    public AuthenticationSuccessHandler successHandler() {
        SimpleUrlAuthenticationSuccessHandler handler =
                new SimpleUrlAuthenticationSuccessHandler();
        handler.setDefaultTargetUrl("/");
        return handler;
    }
    @Bean
    public AuthenticationFailureHandler failureHandler() {
        SimpleUrlAuthenticationFailureHandler handler =
                new SimpleUrlAuthenticationFailureHandler();
        handler.setDefaultFailureUrl("/login?error");
        return handler;
    }


}